package com.struts.interceptor;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.struts2.dispatcher.ServletDispatcherResult;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * Action执行日志追踪拦截器
 * @author LC
 *
 */
public class LoggerInterceptor extends AbstractInterceptor{

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		System.out.println("Action Perform Log ...");
		
		//获取当前Action对象，并打印名称
		Class<? extends Object> currentAction = invocation.getAction().getClass() ;
		String actionName = currentAction.getName() ;
		System.out.println("ActionName：" + actionName);
		
		//获取当前Action代理对象ActionProxy，并打印代理方法——拦截器+动作方法对应的动作方法名称
		ActionProxy currentActionProxy = invocation.getProxy() ;
		String methodName = currentActionProxy.getMethod() ;
		System.out.println("MethodName：" + methodName);
		
		/**
		 * 获取当前请求的request域中的parameter信息，并打印
		 * 		1、获取当前请求的ActionContext对象
		 * 		2、从map栈中取出parameter信息
		 */
		ActionContext actionContext = invocation.getInvocationContext() ;
		Map<String, Object> parameters = actionContext.getParameters() ;
		System.out.print("Parameters{");
		for(Entry<String, Object> entry : parameters.entrySet()) {
			System.out.print(entry.getKey() + ":");
			Object object = entry.getValue() ;
			if(object instanceof String[]) {
				String[] values = (String[])object ;
				for (String value : values) {
					System.out.print(value + ",");
				}
			}
		}
		System.out.println("}");
		//放行，运行后续的拦截器、Action和Result
		String resultString = invocation.invoke() ;
		
		//在Action和Result运行之后，得到Result对象
		 //并且强制转换成ServletDispatcherResult，打印其下一个JSP的位置  
		Result rresult = invocation.getResult() ;
		if (rresult instanceof ServletDispatcherResult){  
            ServletDispatcherResult result = (ServletDispatcherResult) rresult;  
            System.out.println("JSP:"+result.getLastFinalLocation());  
        }  
		System.out.println("Log End ...");
		return resultString;
	}

}
